<?php
/**
 * Created by 岛屿类.
 * User: 尚金殿
 * Date: 2018/8/24
 * Time: 15:44
 */

namespace app\admin\controller;


use think\Db;

class IslandController extends CommonController
{
    protected $mysql = 'island';
    protected $pk = 'id';
    protected $name = 'name';
    protected $status = 'status';


    //岛屿新增
    public function add(){
        if($this->request->isPost()){

            //获取数据
            $data = $this->request->param();

            //判定数据
            if(!$data['name']){
                return show(0,'岛屿名称不能为空');
            }

            if(!isset($data['label'])){
                return show(0,'岛屿标签不能为空');
            }

            //判断有没有主键
            if(!empty($data['id'])){
                $this->save($data);
            }

            //转化岛屿标签
            $data['label'] = implode(',',$data['label']);

            //判定是否有轮播
            if(isset($data['img'])){
                $slider['img'] = implode(',',$data['img']);
                unset($data['img']);
            }

            //入库
            $islandId = $this->getAdd($data);

            //入库轮播表
            if($islandId){
                $slider['island_id'] = $islandId;
                $slider['status'] = 1;
                $res = Db::name('slider')->insertGetId($slider);

                if(!$res){
                    return show(0,'新增失败');
                }
                    return show(1,'新增成功');
            }
        }else{
            //获取岛屿标签
            $label = Db::name('island_label')->where('status','>',-1)->select();

            //变量输出
            $this->assign('label',$label);

            //加载模版
            return $this->fetch();
        }
    }

    //岛屿编辑
    public function edit(){
        $id = $this->request->param('id');

        //获取岛屿信息
        $island = Db::name($this->mysql)->where($this->pk,$id)->find();

        //获取轮播信息
        $img = Db::name('slider')->where('island_id',$id)->find();
        $island['img'] = $img['img'];
        $island['label'] = explode(',',$island['label']);

        //获取岛屿标签
        $label = Db::name('island_label')->where('status','>',-1)->select();
		
        //变量输出
        $this->assign(['island'=>$island,'label' => $label]);

        //加载模版
        return $this->fetch();
    }

    //保存编辑操作
    public function save($data){
        if(!$data || !is_array($data)){
            return show(0,'传递的数据不合法');
        }

        //获取数据
        $id = $data[$this->pk];
        unset($data[$this->pk]);
        $data['update_time'] = time();
        $data['label'] = implode(',',$data['label']);

        //判定有没有轮播
        if(isset($data['img'])){
            $slider['img'] = implode(',',$data['img']);
            unset($data['img']);
        }

        //入库
        $res = Db::name($this->mysql)->where($this->pk,$id)->update($data);

        //轮播表入库
        if($res){
            Db::name('slider')->where('island_id',$id)->update($slider);

            return show(1,'更新成功');
        }
    }
}